package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Lzm
 * @version 1.0
 */
// 只要用户使用点评, 就无限刷新token有效期
public class RefreshInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取token信息
        String token = response.getHeader("authorization");
        // 2. 判断token是否存在
        if (StrUtil.isBlank(token)){
            return true;
        }
        // 3. 获取用户信息
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(LoginConstant.REDIS_USER + token);
        // 4. 判断用户是否登录
        if (map.isEmpty()){
            return true;
        }
        // 5. 将用户信息保存到ThreadLocal中
        UserHolder.saveUser(BeanUtil.fillBeanWithMap(map,new UserDTO(),false));
        return true;
    }
}
